import { fakeNetwork } from "./utils/fake";

// 获取所有联系数据
export async function getContacts(query) {
  const data = await fakeNetwork({
    method: "GET",
    // TODO:这里的json-server全局检索?q=XXX还是有些问题
    url: `/contacts`+(query?`?q=${query}`:""),
  });
  return data;
}

// 创建一个新的联系人
export async function createContact() {
  let id = Math.random().toString(36).substring(2, 9);
  let contact = { id, createdAt: Date.now() };
  await fakeNetwork({
    method: "POST",
    url: "/contacts",
    data: contact,
  });
  return contact;
}

export async function getContact(id) {
  const contact = await fakeNetwork({ method: "get", url: "/contacts/" + id });
  return contact ?? null;
}

// 这里用patch方法进行更新！！！
export async function updateContact(id, updates) {
  await fakeNetwork({ method: "patch", url: `/contacts/${id}`, data: updates });
  const contact = await getContact(id);
  return contact;
}

// 删除联系人
export async function deleteContact(id) {
  await fakeNetwork({ method: "delete", url: `/contacts/${id}` });
}
